import { Component } from 'react'
import Form from "./form.jsx"
import Table from "./table.jsx"
class Curd extends Component {
    constructor() {
        super()
        this.state = {
            list: [{
                id: 1, user: "my", age: 18
            }, {
                id: 2, user: "my2", age: 18
            }, {
                id: 3, user: "my3", age: 18
            }],
            user: "",
            age: "",
            flag: true,
            editId: null
        }
    }
    add=(e)=>{  
    let list=JSON.parse(JSON.stringify(this.state.list))
    list.push(e)
    this.setState({
        list:list
    })
    }
    edit=(id)=>{
        let list = JSON.parse(JSON.stringify(this.state.list))
        let obj = list.find(v => v.id == id)
        this.setState({
            user: obj.user,
            age: obj.age,
            editId: obj.id,
            flag: false
        })
    }
    editOK = () => {
        let list = JSON.parse(JSON.stringify(this.state.list));
        let index = list.findIndex(v => v.id == this.state.editId);
        list[index].user = this.state.user;
        list[index].age = this.state.age;

        this.setState({
            list: list,
            flag: true
        })
    }
    del=(id)=>{
        let list = JSON.parse(JSON.stringify(this.state.list))
        let index = list.findIndex(v => v.id == id)
        list.splice(index, 1)
        this.setState({
            list: list
        })
    }
    change=(event)=>{
        this.setState({
            [event.target.name]: event.target.value
        })
    }
    render() {
        return (
            <div>
                <Form add={this.add} statec={this.state} editOK={this.editOK} flag={this.state.flag} change={this.change}></Form>
                <Table list={this.state.list} edit={this.edit} del={this.del}  ></Table>
            </div>


        )
    }
}

export default Curd